<template>
  <el-card class="box-card">
    <el-button type="primary" :icon="Plus" @click="showSaveOrUpdateTrademark()"
      >添加商品</el-button
    >

    <el-table
      v-loading="loading"
      :data="trademarkList"
      style="width: 100%"
      border
      class="trademark-table"
    >
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌Logo">
        <template v-slot="{ row }">
          <img
            :src="row.logoUrl"
            alt="row.tmName"
            srcset=""
            class="trademark-img"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="showSaveOrUpdateTrademark(row)"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="removeTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="30"
      @size-change="getTrademarkList()"
      @current-change="getTrademarkList()"
    />
    <el-dialog
      v-model="Visible"
      :title="`${trademarkFormData.id ? '修改品牌' : '添加品牌'}`"
      width="30%"
    >
      <el-form
        ref="trademarkFormRef"
        :model="trademarkFormData"
        :rules="trademarkFormRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademarkFormData.tmName" />
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="UPLOAD_URL + '/admin/product/fileUpload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkFormData.logoUrl"
              :src="trademarkFormData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="Visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XTrademark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage,ElMessageBox } from "element-plus";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import {
  getTradeMarklistApi,
  saveTrademarkApi,
  updateTrademarkApi,
  removeTrademarkApi
} from "@/api/product/trademark";
import type {
  TrademarkList,
  getTrademarkItem,
} from "@/api/product/model/trademarkModel";
import type { UploadProps, FormInstance, FormRules } from "element-plus";

const removeTrademark = (row: getTrademarkItem) => {
  ElMessageBox.confirm(
    `您确定要删除${row.tmName}品牌吗?`,
    "删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      await removeTrademarkApi(row.id)
      ElMessage.error('删除成功');
      getTrademarkList();
      
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Delete canceled",
      // });
    });
};

/****************修改品牌***************/
//表单数据
const trademarkFormRef = ref<FormInstance>();
const trademarkFormData = reactive({
  logoUrl: "",
  tmName: "",
  id: 0,
});
const trademarkFormRules = reactive<FormRules>({
  tmName: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 2, max: 12, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "Please input Activity name" }],
});

const submitForm = () => {
  trademarkFormRef.value?.validate(async (valid) => {
    if (valid) {
      const { tmName, logoUrl, id } = trademarkFormData;
      if (id) {
        await updateTrademarkApi({ tmName, logoUrl, id });
      } else {
        await saveTrademarkApi(tmName, logoUrl);
      }

      ElMessage.success(`${id ? "修改" : "添加"}品牌成功`);
      // 将对话框隐藏
      Visible.value = false;
      // 再次获取数据展示
      getTrademarkList();
    }
  });
};

//添加商品
// const AddTrademark = () => {
//   Visible.value = true;
//   trademarkFormRef.value?.clearValidate();
// };
//修改商品
const showSaveOrUpdateTrademark = (
  row: getTrademarkItem = { tmName: "", logoUrl: "", id: 0 }
) => {
  Visible.value = true;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.id = row.id;
  trademarkFormRef.value?.clearValidate();
};

/********************上传图片************* */
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkFormData.logoUrl = response.data;
  trademarkFormRef.value?.clearValidate(["logoUrl"]);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imageTypes = ["image/jpeg", "image/jpg", "image/png"];
  if (!imageTypes.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须是jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传的图片不能超过200kb!");
    return false;
  }
  return true;
};

/******************分页展示******************* */
const UPLOAD_URL = import.meta.env.VITE_API_URL;
const imageUrl = ref("");
const currentPage = ref(1);
const pageSize = ref(3);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const trademarkList = ref<TrademarkList>([]);
const total = ref(0);
const loading = ref(false);
const Visible = ref(false);

const getTrademarkList = async () => {
  loading.value = true;
  const res = await getTradeMarklistApi(currentPage.value, pageSize.value);
  trademarkList.value = res.records;
  total.value = res.total;
  loading.value = false;
};
// const handleSizeChange = (val: number) => {
//   console.log(`${val} items per page`);
// };
// const handleCurrentChange = (val: number) => {
//   console.log(`current page: ${val}`);
// };

onMounted(getTrademarkList);
</script>

<style scoped>
.trademark-table {
  margin: 10px 0;
}
.trademark-img {
  width: 150px;
  height: 100px;
}
</style>
<style>
/* 因为要upload组件样式，所以要定义全局样式或深度选择器 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
